﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    /// <summary>
    /// 这是个工具类，为力求简短，只用了一个字母。
    /// </summary>
    class L
    {
        public static int randomSeed = 0;

        public static String FormatChoiceQuestionTextString(String srcString)
        {
            if (srcString == null)
                return null;
            if (srcString.Length == 0)
                return "";

            return srcString.Replace("\n", "").Replace("\r", "").Replace("\t", "").Replace(" ", "").Replace("　", "").Replace("〓", "");
        }

        public static int randomMinValue = 0;

        //这个方法似乎有问题。是从Java中移植过来的。
        public static int[] GetRandomIntArray(int size)
        {
            int[] send = new int[size];

            for (int i = 0; i < send.Length; i++)
            {
                send[i] = i;
            }

            int temp1, temp2, temp3;
            Random random = new Random(L.randomSeed);
            L.randomSeed += 7;
            if (L.randomSeed >= int.MaxValue - 14) L.randomSeed = 0;

            for (int i = 0; i < send.Length; i++)// 随机交换10次。
            {
                temp1 = random.Next(randomMinValue, randomMinValue + 10) % (send.Length);// 随机产生一个位置。
                randomMinValue += 10;
                if (randomMinValue >= 1000) randomMinValue = 10;

                //System.Threading.Thread.Sleep(7);//否则得到的重复值太多，选7是因为它是质数。

                temp2 = random.Next(randomMinValue, randomMinValue + 10) % (send.Length);// 随机产生另一个位置。
                if (randomMinValue >= 1000) randomMinValue = 10;

                if (temp1 != temp2)
                {
                    temp3 = send[temp1];
                    send[temp1] = send[temp2];
                    send[temp2] = temp3;
                }
            }

            if (randomMinValue >= 1000) randomMinValue = 10;

            return send;
        }

        /// <summary>
        /// 将指定数字转换成字母（1→A，2→B...）。
        /// </summary>
        /// <param name="i">要转换成对应字母的数字。</param>
        public static string ConvertToAlpha(int i)
        {
            if (i < 1 || i > 26) return string.Empty;

            return ((char)((int)'A' + i - 1)).ToString() + "．";
        }

        /// <summary>
        /// 根据键盘上的按键值取对应字母。
        /// </summary>
        /// <param name="key">按键值。</param>
        public static string GetAlpha(Key key)
        {
            if (key >= Key.A && key <= Key.Z)
            {
                return ((char)((int)'A' + key - Key.A)).ToString();
            }

            return string.Empty;
        }

        /// <summary>
        /// 当需要覆盖被预览的图像文件时，会出现“文件被锁定”的问题。这是因为：
        /// BitmapImage没有Dispose()方法，系统虽然删除了image，但是图片文件仍然被当前进程占用着。
        /// 解决的办法是：不再给BitmapImage直赋filePath，而是先根据filePath读取图片的二进制格式，赋给BitmapImage的Source，这样就可以在图片读取完毕后关闭流。
        /// </summary>
        public static BitmapImage BuildBitmapImage(string filePath, out Size size)
        {
            var bitmapImage = new BitmapImage();
            using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
            {
                FileInfo fi = new FileInfo(filePath);
                byte[] bytes = reader.ReadBytes((int)fi.Length);
                reader.Close();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = new MemoryStream(bytes);
                bitmapImage.EndInit();
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                size = new Size(bitmapImage.Width, bitmapImage.Height);
            }
            return bitmapImage;
        }

        private static System.Windows.Media.SolidColorBrush themeBrown = new System.Windows.Media.SolidColorBrush(
            new System.Windows.Media.Color() { A = 255, R = 153, G = 121, B = 86, });
        /// <summary>
        /// 不好记。
        /// </summary>
        public static System.Windows.Media.SolidColorBrush ThemeBrown => themeBrown;

        /// <summary>
        /// 获取 Ctrl/Shift/Alt 这三组功能键的状态。
        /// </summary>
        public static void GetKeyboardState(out bool isAlt, out bool isShift, out bool isCtrl)
        {
            isCtrl = false;
            isShift = false;
            isAlt = false;
            if ((Keyboard.GetKeyStates(Key.LeftCtrl) & KeyStates.Down) > 0 || (Keyboard.GetKeyStates(Key.RightCtrl) & KeyStates.Down) > 0) isCtrl = true;
            if ((Keyboard.GetKeyStates(Key.LeftShift) & KeyStates.Down) > 0 || (Keyboard.GetKeyStates(Key.RightShift) & KeyStates.Down) > 0) isShift = true;
            if ((Keyboard.GetKeyStates(Key.LeftAlt) & KeyStates.Down) > 0 || (Keyboard.GetKeyStates(Key.RightAlt) & KeyStates.Down) > 0) isAlt = true;
        }



        #region Post请求 
        /// <summary>
        /// psot请求 key-value 
        /// 本方法修改自：https://www.cnblogs.com/dyd520/p/13638912.html 
        /// </summary>
        /// <param name="url">请求连接</param>
        /// <param name="parms">请求参数 字典类型</param>
        /// <param name="statusCode">请求状态码</param>
        /// <returns></returns>
        public static string HttpPost(string url, Dictionary<string, string> parms, out string statusCode)
        {
            try
            {
                string result = string.Empty;
                //设置Http的正文
                FormUrlEncodedContent httpContent = new FormUrlEncodedContent(parms);

                using (HttpClient httpClient = new HttpClient())
                {
                    //异步Post
                    HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
                    //输出Http响应状态码
                    statusCode = response.StatusCode.ToString();
                    //确保Http响应成功
                    if (response.IsSuccessStatusCode)
                    {
                        //异步读取json
                        result = response.Content.ReadAsStringAsync().Result;
                    }
                }
                return result;
            }
            catch (HttpRequestException e)
            {
                statusCode = "500";
                return e.Message;
            }
        }

        public static IronPython.Runtime.PythonTuple HttpPost(string url, IronPython.Runtime.PythonDictionary paramsDict)
        {
            try
            {
                var dict = new Dictionary<string, string>();
                if (paramsDict != null && paramsDict.Count > 0)
                {
                    foreach (var item in paramsDict)
                    {
                        dict.Add(item.Key.ToString(), item.Value.ToString());
                    }
                }

                string result = string.Empty;
                string statusCode = string.Empty;

                //设置Http的正文
                FormUrlEncodedContent httpContent = new FormUrlEncodedContent(dict);

                using (HttpClient httpClient = new HttpClient())
                {
                    //异步Post
                    HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
                    //输出Http响应状态码
                    statusCode = response.StatusCode.ToString();
                    //确保Http响应成功
                    if (response.IsSuccessStatusCode)
                    {
                        //异步读取json
                        result = response.Content.ReadAsStringAsync().Result;
                    }
                }
                var resultTuple = new IronPython.Runtime.PythonTuple(new string[] { statusCode, result });
                return resultTuple;
            }
            catch (HttpRequestException e)
            {
                var statusCode = "500";
                return new IronPython.Runtime.PythonTuple(new string[] { statusCode, e.Message });
            }
        }
        #endregion

        /// <summary>
        /// 发送Get请求
        /// 此方法改自：https://www.jb51.net/article/222582.htm
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="dic">请求参数定义</param>
        /// <returns></returns>
        public static string HttpGet(string url, Dictionary<string, string> dic)
        {
            string result = "";
            StringBuilder builder = new StringBuilder();
            builder.Append(url);
            if (dic.Count > 0)
            {
                builder.Append("?");
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
            }
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
            //添加参数
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            try
            {
                //获取内容
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            finally
            {
                stream.Close();
            }
            return result;
        }

        public static IronPython.Runtime.PythonTuple HttpGet(string url, IronPython.Runtime.PythonDictionary parms)
        {
            var dict = new Dictionary<string, string>();
            if (parms != null && parms.Count > 0)
            {
                foreach (var item in parms)
                {
                    dict.Add(item.Key.ToString(), item.Value.ToString());
                }
            }

            string result = "";
            StringBuilder builder = new StringBuilder();
            builder.Append(url);
            if (dict.Count > 0)
            {
                builder.Append("?");
                int i = 0;
                foreach (var item in dict)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
            }
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
            //添加参数
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            try
            {
                //获取内容
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                return new IronPython.Runtime.PythonTuple(new string[] { resp.StatusCode.ToString(), ex.Message });
            }
            finally
            {
                stream.Close();
            }
            return new IronPython.Runtime.PythonTuple(new string[] { resp.StatusCode.ToString(), result });
        }
    
    }
}
